#include "head.h"

int insertFile(const char *filename,const int cur_dir_id,const char* md5,const int filesize,char *error_buf)
{
    //建立mysql连接
    if(cur_dir_id<=0)
    {
        /* printf("id is not legal\n"); */
        strcpy(error_buf,"id is not legal!");
        return -1;
    }
    MYSQL* mysql=mysql_init(NULL);
    MYSQL* ret=mysql_real_connect(mysql,"localhost","root","123","OnlineStorage",0,NULL,0);
    if(ret==NULL)
    {
        sprintf(error_buf,"%s:%s","mysql_real_connect",mysql_error(mysql));
        return -1;
    }

    char sql[4096]={0};

    //1.先判断有无重名文件
    sprintf(sql,"select filename from vft where parent_id=%d and type='f'and filename='%s';",cur_dir_id,filename);
    int qret=mysql_query(mysql,sql);
    printf("sql=%s\n",sql);
    if(qret!=0)
    {
        sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES* rows=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(rows);
    if(mysql_num_rows(rows)!=0)
    {
        strcpy(error_buf,"exit same name file!\n"); 
        return -1; 
    }
    /* if(rows!=NULL) */
    /* { */
    /*     //说明有重名文件 */
    /*     strcpy(error_buf,"exit same name file!\n"); */
    /*     return -1; */
    /* } */

    //无重名文件,找当前目录的信息
    sprintf(sql,"select user,path from vft where id=%d;",cur_dir_id);
    printf("sql=%s\n",sql);
    qret=mysql_query(mysql,sql);
    if(qret!=0)
    {
        sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
        return -1;
    }
    rows=mysql_store_result(mysql);
    row=mysql_fetch_row(rows);

    //row[0]是user,row[1]是目录的path
    char file_path[500]={0};
    strcpy(file_path,row[1]);
    printf("file_path=%s\n",file_path);
    strcat(file_path,"/");
    strcat(file_path,filename);
    printf("file_path=%s\n",file_path);
    bzero(sql,sizeof(sql));
    sprintf(sql,"INSERT INTO vft (filename,user,parent_id,md5,type,path,size)VALUES('%s','%s',%d,'%s','f','%s',%d);",filename,row[0],cur_dir_id,md5,file_path,filesize);
    qret=mysql_query(mysql,sql);
    printf("sql=%s\n",sql);
    if(qret!=0)
    {
        sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
        return -1;
    }

    mysql_close(mysql);
    return 0;
} 
